package com.bawei.search.vm

import androidx.lifecycle.viewModelScope
import com.bawei.common.vm.BaseViewModel
import com.bawei.search.intent.SearchViewIntent
import com.bawei.search.model.SearchRepository
import com.bawei.search.state.SearchUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2025/2/5
 * Desc: 搜索ViewModel
 */

@HiltViewModel
class SearchViewModel @Inject constructor(private val repository: SearchRepository): BaseViewModel<SearchViewIntent>(){
    private val _uiState = MutableStateFlow<SearchUiState>(SearchUiState.LoadEmpty)
    val uiState: StateFlow<SearchUiState> = _uiState.asStateFlow()


    override fun dispatchIntent(intent: SearchViewIntent) {
        when(intent){
            is SearchViewIntent.LoadSimpleVideoListByKeyword -> loadSimpleVideoList(intent.keyword, intent.page, intent.pageSize)
        }
    }

    private fun loadSimpleVideoList(keyword: String, page: Int, pageSize: Int){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                repository.getSimpleVideoByKeyword(keyword, page, pageSize).collect{ list ->
                    if (list.isNotEmpty()){
                        _uiState.value = SearchUiState.LoadSimpleVideoSuccess(list)
                    } else{
                        _uiState.value = SearchUiState.LoadSimpleVideoFail("没有数据")
                    }
                }
            } catch (e:Exception){
                e.printStackTrace()
                _uiState.value = SearchUiState.LoadSimpleVideoFail("请求失败！！")
            } finally {
                cancel()
            }
        }




    }


}